﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace WeChatParking.Core.Payment.UnionPay
{
    public class UnionPayCommon
    {
        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="param"></param>
        /// <param name="appkey"></param>
        /// <returns></returns>
        public static String signParam(string param, String appkey)
        {

            return System.Web.HttpUtility.UrlEncode(HMACMD5Encrypt(param, appkey));
        }
        /// <summary>
        ///验签
        /// </summary>
        /// <param name="param"></param>
        /// <param name="appkey"></param>
        /// <param name="sign"></param>
        /// <returns></returns>
        public static bool CheckSign(string param, String appkey, string sign)
        {
            string Ysign = HMACMD5Encrypt(param, appkey);
             Ysign= System.Web.HttpUtility.UrlEncode(Ysign, Encoding.UTF8);
            //sign = System.Web.HttpUtility.UrlEncode(sign, Encoding.UTF8);
            //sign = System.Web.HttpUtility.UrlEncode(sign, Encoding.UTF8);
            sign = HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(sign));
           // sign = sign.Replace("%3d", "=");
            //System.Web.HttpUtility.UrlEncode.encode(UrlEncode.encode(sign, "UTF-8"), "UTF-8");
            return sign.Equals(Ysign);
        }
        public static bool CheckSign2(string param, String appkey, string sign)
        {
            string Ysign = HMACMD5Encrypt(param, appkey);
            Ysign = System.Web.HttpUtility.UrlEncode(Ysign, Encoding.UTF8);
            return (sign.ToUpper()).Equals(Ysign.ToUpper());
        }
        /// <summary>
        /// HMACMD5加密
        /// </summary>
        /// <param name="data">需要加密的字符串</param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string HMACMD5Encrypt(string data, string key)
        {
            System.Security.Cryptography.HMACMD5 provider = new System.Security.Cryptography.HMACMD5(System.Text.Encoding.UTF8.GetBytes(key));
            byte[] hashedPassword = provider.ComputeHash(System.Text.Encoding.UTF8.GetBytes(data));
            //return System.Web.HttpUtility.UrlEncode(Convert.ToBase64String(hashedPassword));
            return Convert.ToBase64String(hashedPassword);
        }
    }
}
